from tortoise.expressions import Q

from app.core.crud import CRUDBase
from app.models.appointment import AppointmentCategory
from app.schemas.appointment import AppointmentCategoryCreate,AppointmentCategoryUpdate


class CategoryController(CRUDBase[AppointmentCategory, AppointmentCategoryCreate, AppointmentCategoryUpdate]):
    def __init__(self):
        super().__init__(model=AppointmentCategory)

    async def get_tree(self):
        alls = await self.model.all().order_by("order")

        # 辅助函数，用于递归构建分类树
        def build_tree(parent_id):
            return [
                {
                    "id": item.id,
                    "name": item.name,
                    "desc": item.desc,
                    "order": item.order,
                    "parent_id": item.parent_id,
                    "children": build_tree(item.id),  # 递归构建子分类
                }
                for item in alls
                if item.parent_id == parent_id
            ]

        # 从顶级（parent_id=0）开始构建分类树
        tree = build_tree(0)
        return tree

    async def list_category(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict() for obj in objs]
        return total, data

    async def get_category(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def create_category(self, obj_in: AppointmentCategoryCreate):
        await self.create(obj_in=obj_in)
        return True

    async def update_category(self, obj_in: AppointmentCategoryUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def delete_category(self, data_id: int):
        await self.remove(id=data_id)
        return True

    async def get_with_children(self,parent_id: int):
        menu = await category_controller.model.get(id=parent_id)
        menu_dict = await menu.to_dict()
        child_menus = await category_controller.model.filter(parent_id=parent_id).order_by("order")
        menu_dict["children"] = [await self.get_with_children(child.id) for child in child_menus]
        return menu_dict

category_controller = CategoryController()
